package com.kele.pay.service;

import com.github.wxpay.sdk.WXPayUtil;
import com.kele.common.model.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class WxPayService_RestTemplate {


    @Autowired
    RestTemplate restTemplate;

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.partner}")
    private String partner;

    @Value("${weixin.partnerkey}")
    private String partnerkey;

    @Value("${weixin.notifyurl}")
    private String notifyurl;

    public Result unifiedOrder(Long orderId, Integer total_fee, String body) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/xml; charset=UTF-8");
        headers.setContentType(mediaType);
        headers.add("Accept", MediaType.APPLICATION_XML_VALUE.toString());

        //准备接口参数
        Map<String,String> map = new HashMap<>();
        map.put("appid",appid);
        map.put("mch_id",partner);
        map.put("nonce_str",WXPayUtil.generateNonceStr());

        map.put("body",body);
        map.put("out_trade_no",orderId.toString());
        map.put("total_fee",total_fee.toString());
        map.put("spbill_create_ip","127.0.0.1");
        map.put("notify_url",notifyurl);
        map.put("trade_type","NATIVE");

        String content = WXPayUtil.generateSignedXml(map, partnerkey);

        HttpEntity entity = new HttpEntity(content, headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(
                "https://api.mch.weixin.qq.com/pay/unifiedorder",
                entity, String.class);
        String response_body_xml = stringResponseEntity.getBody();

        System.out.println(response_body_xml);

        return null;

    }
}
